﻿using _RobotInspection.DTO;
using _RobotInspection.Entities;
using _RobotInspection.Interfaces;
using _RobotInspection.Models;
using Models;
using RobotInspection.Entities;
using SqlSugar;

namespace _RobotInspection.Services
{
    /// <summary>
    /// 关注事项相关功能服务层实现类
    /// </summary>
    public class AttentionItemService :IAttentionItemService
    {
        private readonly ISqlSugarClient _db;
        private readonly ILogger<AttentionItemService> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public AttentionItemService(ISqlSugarClient db, ILogger<AttentionItemService> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 异步分页查询关注事项
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        public async Task<ApiResponse<AttentionItemPagedResultDto>> GetAttentionItemsPagedAsync(AttentionItemPagedDto queryDto)
        {
            try
            { 
                // 联表查询
                var queryable = _db.Queryable<attention_item>()
                    .LeftJoin<inspection_records>((ai, ir) => ai.record_id == ir.id)
                    .LeftJoin<inspection_items>((ai, ir, ii) => ir.item_id == ii.id)
                    .LeftJoin<equipment>((ai, ir, ii, e) => ii.equipment_id == e.id)
                    .LeftJoin<users>((ai, ir, ii, e, u) => ai.user_id == u.id);

                // 按要求添加查询条件
                if (!string.IsNullOrWhiteSpace(queryDto.Unit))
                {
                    queryable = queryable.Where((ai, ir, ii, e, u) => e.unit.Contains(queryDto.Unit));
                }
                if (!string.IsNullOrWhiteSpace(queryDto.EquipmentName))
                {
                    queryable = queryable.Where((ai, ir, ii, e, u) => e.equipment_name.Contains(queryDto.EquipmentName));
                }
                if (queryDto.UserId.HasValue)
                {
                    queryable = queryable.Where((ai, ir, ii, e, u) => u.id == queryDto.UserId);
                }
                if (!string.IsNullOrWhiteSpace(queryDto.AbnormalName))
                {
                    queryable = queryable.Where((ai, ir, ii, e, u) => ai.abnormal_name.Contains(queryDto.AbnormalName));
                }

                // 获取总记录数
                var totalCount = await queryable.CountAsync();

                // 准备返回数据
                var attentionItemResultDtoList = await queryable.Select((ai, ir, ii, e, u) => new AttentionItemResultDto
                {
                    Id = ai.id,
                    AbnormalName = ai.abnormal_name,
                    Unit = e.unit,
                    EquipmentName = e.equipment_name,
                    ReporterRealName = u.real_name,
                    AbnormalDescription = ai.abnormal_description,
                    ReportedAt = ai.reported_at
                }).ToPageListAsync(queryDto.PageIndex, queryDto.PageSize);

                //判断总页数
                var totalPages = 0;
                if (totalCount % queryDto.PageSize > 0)
                {
                    totalPages = totalCount / queryDto.PageSize + 1;
                }
                else
                {
                    totalPages = totalCount / queryDto.PageSize;
                }

                //准备返回数据
                var attentionItemPagedResultDto = new AttentionItemPagedResultDto
                {
                    AttentionItemResultList = attentionItemResultDtoList,
                    TotalCount = totalCount,
                    TotalPages = totalPages,
                    CurrentPage = queryDto.PageIndex,
                    PageSize = queryDto.PageSize,
                    HasPreviousPage = queryDto.PageIndex > 1,
                    HasNextPage = queryDto.PageIndex < totalPages
                };

                var message = $"查询到关注事项总数：{totalCount}";

                return ApiResponse<AttentionItemPagedResultDto>.Success(attentionItemPagedResultDto, message, totalCount);
            }
            catch (Exception ex)
            {
                return ApiResponse<AttentionItemPagedResultDto>.Error($"查询失败：{ex.Message}", 500);
            }
        }

        /// <summary>
        /// 异步按id查询关注事项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse<attention_item>> GetAttentionItemByIdAsync(long id)
        {
            // 检验数据是否合法
            if (id <= 0)
            {
                return ApiResponse<attention_item>.Error("查询失败：关注事项ID无效", 400);
            }

            try
            {
                var attentionItemList = await _db.Queryable<attention_item>().Where(ai => ai.id == id).ToListAsync();
                if (attentionItemList.Count == 1)
                {
                    var attentionItem = await _db.Queryable<attention_item>().Where(ai => ai.id == id) .FirstAsync();
                    return ApiResponse<attention_item>.Success(attentionItem, null);
                }
                else
                {
                    return ApiResponse<attention_item>.Error("查询失败：关注事项不存在", 400);
                }
            }
            catch (Exception ex)
            {
                return ApiResponse<attention_item>.Error($"查询失败：{ex.Message}", 500);
            }
        }

        /// <summary>
        /// 异步创建关注事项
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        public async Task<ApiResponse<attention_item>> InsertAttentionItemAsync(AttentionItemDto queryDto)
        {
            // 检验数据是否合法
            if (queryDto.RecordId <= 0)
            {
                return ApiResponse<attention_item>.Error("关注事项创建失败：点检记录ID不合法", 400);
            }
            if (queryDto.UserId <= 0)
            {
                return ApiResponse<attention_item>.Error("关注事项创建失败：上报人ID不合法", 400);
            }
            if (string.IsNullOrWhiteSpace(queryDto.AbnormalName))
            {
                return ApiResponse<attention_item>.Error("关注事项创建失败：需要异常名称", 400);
            }

            try
            {
                // 检验外键是否存在
                var inspectionRecordNumber = await _db.Queryable<inspection_records>().Where(ir => ir.id == queryDto.RecordId).CountAsync();
                if (inspectionRecordNumber != 1)
                {
                    return ApiResponse<attention_item>.Error("关注事项创建失败：点检记录不存在", 400);
                }
                var userNumber = await _db.Queryable<users>().Where(u => u.id == queryDto.UserId).CountAsync();
                if (userNumber != 1)
                {
                    return ApiResponse<attention_item>.Error("关注事项创建失败：上报人不存在", 400);
                }

                // 准备关注事项数据
                var attentionItem = new attention_item
                {
                    record_id = queryDto.RecordId,
                    user_id = queryDto.UserId,
                    abnormal_name = queryDto.AbnormalName,
                    abnormal_description = queryDto.AbnormalDescription,
                    reported_at = DateTime.Now
                };

                // 插入关注事项数据
                var attentionItemResult = await _db.Insertable(attentionItem).ExecuteReturnEntityAsync();

                return ApiResponse<attention_item>.Success(attentionItemResult, "关注事项创建成功");
            }
            catch (Exception ex)
            {
                return ApiResponse<attention_item>.Error($"关注事项创建失败：{ex.Message}", 500);
            }
        }

        /// <summary>
        /// 异步删除关注事项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse<attention_item?>> DeleteAttentionItemAsync(long id)
        {
            // 检验数据是否合法
            if (id <= 0)
            {
                return ApiResponse<attention_item?>.Error("关注事项删除失败：点检记录ID不合法", 400);
            }

            try
            {
                var attentionItemNumber = await _db.Queryable<attention_item>().Where(ai => ai.id == id).CountAsync();
                if (attentionItemNumber == 1)
                {
                    await _db.Deleteable<attention_item>().Where(ai => ai.id == id).ExecuteCommandAsync();
                    return ApiResponse<attention_item?>.Success(null, "关注事项删除失败");
                }
                else
                {
                    return ApiResponse<attention_item?>.Error("关注事项删除失败：关注事项不存在", 400);
                }
            }
            catch (Exception ex)
            {
                return ApiResponse<attention_item?>.Error($"关注事项删除失败：{ex.Message}", 500);
            }
        }
    }
}
